package com.huang.config;

import com.huang.util.JwtUtils;
import com.huang.util.WebUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      //关闭跨域
        http.csrf().disable();

        //配置登录url
        http.formLogin()
                .successHandler(successHandler())
                .failureHandler(failureHandler());
        //设置需要认证与拒绝访问的异常处理器
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint());
        //3.放行登录url(不需要认证就可以访问)
        http.authorizeRequests()
                .anyRequest().authenticated();

    }
    //认证成功处理器
  public AuthenticationSuccessHandler successHandler(){
        return (request,response,authentication) -> {
            User principal = (User)authentication.getPrincipal();
            Map<String,Object> map=new HashMap<>();
            map.put("state", 200);
            map.put("message", "欢迎你登录");
            Map<String,Object> jwtmap=new HashMap<>();
            jwtmap.put("username", principal.getUsername());
            List<String> authlist=new ArrayList<>();
            principal.getAuthorities().forEach((author)->{
                authlist.add(author.getAuthority());
            } );
         jwtmap.put("authorities",authlist);
         String token= JwtUtils.generatorToken(jwtmap);
         map.put("token", token);
            WebUtils.writeJsonToClient(response, map);


        };
  }
  //认证失败处理器
    public AuthenticationFailureHandler failureHandler(){

       return (request, response,  e) -> {
           Map<String,Object> map=new HashMap<>();
           map.put("state",500);
           map.put("msg","username or password error");
           WebUtils.writeJsonToClient(response,map);
           };
       }

    //没有认证时执行DefaultAuthenticationEntryPoint对象
    public AuthenticationEntryPoint authenticationEntryPoint(){
        return (request, response, e)->{
            Map<String,Object> map=new HashMap<>();
            map.put("state",401);//SC_UNAUTHORIZED 的值为401
            map.put("message","请先登录再访问");
            WebUtils.writeJsonToClient(response,map);
        };
    }


}
